package example.documentbased.editorModule.controller
{
	import example.documentbased.editorModule.models.EditorModuleModel;
	import example.documentbased.mainModule.models.vo.DocumentVO;
	import example.documentbased.mainModule.services.delegates.IMainServiceDelegate;
	
	import org.etherframework.common.command.IProcessingDispatcher;
	import org.etherframework.controller.IReactiveCommand;
	import org.etherframework.controller.ReactiveCommand;
	
	import raix.reactive.IObservable;
	import raix.reactive.Observable;
	import raix.reactive.Unit;
	
	public class SaveDocumentCommand extends ReactiveCommand implements IProcessingDispatcher
	{
		private var _document:DocumentVO;
		private var _serviceDelegate:IMainServiceDelegate;
		private var _editorController:IEditorController;
		private var _editorModel:EditorModuleModel;
		
		public function SaveDocumentCommand(serviceDelegate:IMainServiceDelegate, 
											editorController:IEditorController, 
											editorModel:EditorModuleModel)
		{
			_serviceDelegate = serviceDelegate;
			_editorController = editorController;
			_editorModel = editorModel;
		}
		
		public function initialize(document:DocumentVO):IReactiveCommand
		{
			_document = document;
			markAsInitialized();
			
			return this;
		}
		
		override public function observable():IObservable
		{
			return processing(_serviceDelegate.saveDocument(_document)
				.mapMany(function(id:String):IObservable
				{
					_document.id = id;
					
					_editorModel.uneditDocument(_document);
					
					_editorModel.lastSavedDocument = _document;
					
					return  ether.context is RefreshContext ? 
						_editorController.getRefreshAllCommand().observable() :
						Observable.value(new Unit());
				}));
		}
	}
}